﻿using Message_Board.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Message_Board.Controllers
{
    
    public class UsersController : Controller
    {
        private UserDBContext db = new UserDBContext();
        // GET: Users
        public ActionResult Index()//登录页面
        {
            HttpContext.Application.Set("userID", ""+-1);
            HttpContext.Application.Set("userName", "null");
            return View();
        }

        public ActionResult Details(int id)//个人明细
        {
            int i = int.Parse(HttpContext.Application["userID"].ToString());
            if(i==-1)
                return  RedirectToAction("Index", "Users");
            User u = db.Users.Find(i);
            if (u == null)
            {
                return HttpNotFound();
            }
            return View(u);
        }
        public ActionResult Login(User user)//登录
        {
            var u = from m in db.Users where m.ID == user.ID select m;
            if(u.Count() == 0)
                return RedirectToAction("Index", "Users");
            if (u.First() != null)
            {
                string url = "/Users/Details?id="+ user.ID;
                HttpContext.Application.Set("userID", ""+user.ID);
                HttpContext.Application.Set("userName", u.First().Name);
                string s = HttpContext.Application["userName"].ToString();
                return Redirect(url);
            }
            return RedirectToAction("Index", "Users");
        }

        public ActionResult Create()//注册
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(User user)
        {
            if (ModelState.IsValid)
            {
                db.Users.Add(user);
                db.SaveChanges();
                string url = "/Users/Details?id=" + user.ID;
                return Redirect(url);
            }
            return View(user);
        }

        public ActionResult Edit(int id)//修改
        {
            User user = db.Users.Find(id);  //查找给定主键的实体
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        [HttpPost]
        public ActionResult Edit(User user)
        {
            if (ModelState.IsValid)
            {
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
                string url = "/Users/Details?id=" + user.ID;
                return Redirect(url);
            }
            return View(user);
        }

        public ActionResult Quit()//注销
        {
            HttpContext.Application.Set("userID", "" + -1);
            HttpContext.Application.Set("userName", "null");
            return RedirectToAction("Index","Users");
        }
    }
}